package com.example.capsule_chat0322.request;


import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.example.capsule_chat0322.bean.ChatRecordBean;
import com.example.capsule_chat0322.bean.GroupMessageBean;
import com.example.capsule_chat0322.bean.MessageBean;
import com.example.capsule_chat0322.bean.Msg;
import com.example.capsule_chat0322.bean.OneToOneMessageBean;
import com.example.capsule_chat0322.bean.UserInfoBean;
import com.example.capsule_chat0322.configuration.Constant;
import com.example.capsule_chat0322.configuration.HttpConstant;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.global.GlobalThreadPool;
import com.example.capsule_chat0322.global.LRUCache;
import com.example.capsule_chat0322.utils.AlterUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @Author zhuzhiming
 * @Date 2022/5/3 22:38
 */
public class MessagesRequest {

    public static void getMessages(Handler handler, String roomName) {

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(HttpConstant.HTTP_PREFIX + "/getGroupMessages/" + roomName)
                .build();

        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Object context = GlobalAssistMap.getObject("context");
                AlterUtils.alertByToastInSonThread((Context) context, "获取消息列表失败");
            }

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (response.code() != 200) {
                    return;
                }

                String messages = response.body().string();
                List<GroupMessageBean> messageList = new Gson().fromJson(messages, new TypeToken<List<GroupMessageBean>>() {
                }.getType());


                List<Msg> msgList = new ArrayList<>();
                String userId = (String) GlobalAssistMap.getObject("userId");
                if (userId == null) {
                    try {
                        Thread.sleep(100);
                        userId = (String) GlobalAssistMap.getObject("userId");
                        if (userId == null) {
                            Thread.sleep(200);
                            userId = (String) GlobalAssistMap.getObject("userId");
                            if (userId == null) {
                                Thread.sleep(500);
                                userId = (String) GlobalAssistMap.getObject("userId");
                            }
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                if (userId == null) {
                    return;
                }


                int size = messageList.size();

                if (size > 30) {

                    for (int i = 0; i < 10; i++) {
                        GlobalAssistMap.putObject(i + "msgList", new ArrayList<Msg>());
                    }

                    int step = size / 10;

                    CountDownLatch countDownLatch = new CountDownLatch(10);

                    for (int i = 0; i < 10; i++) {
                        int finalI = i;
                        String finalUserId = userId;
                        GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                            @Override
                            public void run() {

                                List<Msg> cacheList = (List<Msg>) GlobalAssistMap.getObject(finalI + "msgList");

                                for (int j = finalI * step; j < (finalI == 9 ? size : finalI * step + step); j++) {
                                    initGroupMessage(messageList.get(j), cacheList, finalUserId, roomName);
                                }
                                countDownLatch.countDown();
                            }
                        });
                    }
                    try {
                        countDownLatch.await();

                        for (int i = 0; i < 10; i++) {
                            List<Msg> cacheList = (List<Msg>) GlobalAssistMap.getObject(i + "msgList");
                            msgList.addAll(cacheList);
                            GlobalAssistMap.removeObject(i + "msgList");
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    for (GroupMessageBean groupMessageBean : messageList) {
                        initGroupMessage(groupMessageBean, msgList, userId, roomName);
                    }
                }

                handler.sendMessage(handler.obtainMessage(1, msgList));
            }
        });


    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private static void initGroupMessage(GroupMessageBean groupMessageBean, List<Msg> msgList, String userId, String roomName) {

        String senderId = groupMessageBean.getSenderId();

        if (!senderId.equals(userId)) {
            final UserInfoBean[] userInfoBean = {(UserInfoBean) GlobalAssistMap.getObject(senderId + "Info")};
            if (userInfoBean[0] == null) {
                UserInfoRequest.doGetUserInfoRequest(new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(@NonNull Message message) {
                        return true;
                    }
                }), senderId);
            }
        }

        if (groupMessageBean.getMsgType() != 0) {

            int type = userId.equals(senderId) ? Msg.TYPE_SEND : Msg.TYPE_RECEIVE;
            if (type == Msg.TYPE_SEND) {

                Msg msg = null;

                if (groupMessageBean.getSignStatus() == 2) {
                    msg = new Msg(groupMessageBean.getSenderId(), Msg.TYPE_SEND, Msg.RECALL_TYPE, "", groupMessageBean.getRoomName(), groupMessageBean.getSenderAvatarLocalPath(), null,false);
                    msgList.add(msg);
                    return;
                }

                if (groupMessageBean.getMsgType() == 1) {
                    msg = new Msg(groupMessageBean.getSenderId(), type, Msg.Other_FILE_TYPE, groupMessageBean.getFilePath(), roomName, groupMessageBean.getSenderAvatarLocalPath(), null,false);
                } else if (groupMessageBean.getMsgType() == 2) {
                    String suf = groupMessageBean.getFileSize();
                    msg = new Msg(groupMessageBean.getSenderId(), type, Msg.Other_FILE_TYPE, groupMessageBean.getFilePath(), roomName, groupMessageBean.getSenderAvatarLocalPath(), groupMessageBean.getFilePath().substring(groupMessageBean.getFilePath().lastIndexOf("/") + 1) + " " + suf,false);
                } else if (groupMessageBean.getMsgType() == 3) {


                    String videoCacheKey = groupMessageBean.getFilePath().substring(groupMessageBean.getFilePath().lastIndexOf("/") + 1);

                    LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                    Bitmap bitmap = (Bitmap) lruCache.get(videoCacheKey);
                    //Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(videoCacheKey);
                    if (bitmap == null) {
                        getVideoImage(groupMessageBean.getContent());
                    }
                    String filePath = groupMessageBean.getContent();


                    filePath = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf(".")) + ".mp4 ";
                    msg = new Msg(groupMessageBean.getSenderId(), type, Msg.Other_FILE_TYPE, groupMessageBean.getFilePath(), roomName, groupMessageBean.getSenderAvatarLocalPath(), filePath,false);
                }
                assert msg != null;
                msg.setId(groupMessageBean.getId());
                msgList.add(msg);

            } else {

                String fileServerPath = groupMessageBean.getContent();

                if (fileServerPath == null) {
                    return;
                }

                String senderAvatarPath = (groupMessageBean.getSenderAvatarServerPath() == null || groupMessageBean.getSenderAvatarServerPath().equals("")) ? groupMessageBean.getSenderAvatarLocalPath() : groupMessageBean.getSenderAvatarServerPath();

                if (senderAvatarPath.contains("/")) {

                    senderAvatarPath = Constant.IMAGE_PATH + senderAvatarPath.substring(senderAvatarPath.lastIndexOf("/") + 1);

                    String finalSenderAvatarPath = senderAvatarPath;

                    LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                    final Bitmap[] bitmap = {(Bitmap) lruCache.get(finalSenderAvatarPath.substring(finalSenderAvatarPath.lastIndexOf("/")))};
                    // final Bitmap[] bitmap = {(Bitmap) GlobalAssistMap.getObject(finalSenderAvatarPath.substring(finalSenderAvatarPath.lastIndexOf("/")))};
                    if (bitmap[0] == null) {
                        bitmap[0] = BitmapFactory.decodeFile(finalSenderAvatarPath);
                        if (bitmap[0] == null) {
                            UserInfoRequest.getAvatar(new Handler(new Handler.Callback() {
                                @Override
                                public boolean handleMessage(@NonNull Message message) {
                                    GlobalAssistMap.putObject(groupMessageBean.getSenderId() + "Avatar", finalSenderAvatarPath);
                                    bitmap[0] = BitmapFactory.decodeFile(finalSenderAvatarPath);
                                    lruCache.put(finalSenderAvatarPath.substring(finalSenderAvatarPath.lastIndexOf("/")), bitmap[0]);
                                    //GlobalAssistMap.putObject(finalSenderAvatarPath.substring(finalSenderAvatarPath.lastIndexOf("/")), bitmap[0]);
                                    return true;
                                }
                            }), groupMessageBean.getSenderAvatarServerPath());
                        } else {
                            lruCache.put(finalSenderAvatarPath.substring(finalSenderAvatarPath.lastIndexOf("/")), bitmap[0]);
                            //GlobalAssistMap.putObject(finalSenderAvatarPath.substring(finalSenderAvatarPath.lastIndexOf("/")), bitmap[0]);
                        }

                    }

                }

                GlobalAssistMap.putObject(groupMessageBean.getSenderId() + "Avatar", senderAvatarPath);

                if (groupMessageBean.getSignStatus() == 2) {
                    Msg msg = new Msg(groupMessageBean.getSenderId(), groupMessageBean.getRoomName(), Msg.RECALL_TYPE, null, Msg.TYPE_RECEIVE, senderAvatarPath,false);
                    msgList.add(msg);
                    return;
                }

                if (groupMessageBean.getMsgType() == 1) {
                    String cacheKey = groupMessageBean.getFilePath().substring(groupMessageBean.getFilePath().lastIndexOf("/") + 1);

                    LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                    Bitmap bitmap = (Bitmap) lruCache.get(cacheKey);
                    //Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(cacheKey);
                    if (bitmap == null) {
                        MessagesRequest.getImage(fileServerPath,null);
                    }
                    Msg msg = new Msg(groupMessageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, cacheKey, roomName, senderAvatarPath, null,false);
                    msg.setId(groupMessageBean.getId());
                    msgList.add(msg);
                } else if (groupMessageBean.getMsgType() == 2) {
                    Msg msg = new Msg(groupMessageBean.getSenderId(), type, Msg.Other_FILE_TYPE, groupMessageBean.getContent(), roomName, senderAvatarPath, groupMessageBean.getFilePath().substring(groupMessageBean.getFilePath().lastIndexOf("/") + 1) + "  " + groupMessageBean.getFileSize(),false);
                    msg.setId(groupMessageBean.getId());
                    msgList.add(msg);
                } else if (groupMessageBean.getMsgType() == 3) {

                    String cacheKey = groupMessageBean.getContent().substring(groupMessageBean.getContent().lastIndexOf("/") + 1);

                    LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                    Bitmap bitmap = (Bitmap) lruCache.get(cacheKey);
                    //Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(cacheKey);
                    if (bitmap == null) {
                        getVideoImage(groupMessageBean.getContent());
                    }
                    String filePath = groupMessageBean.getContent();
                    filePath = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf(".")) + ".mp4 ";
                    Msg msg = new Msg(groupMessageBean.getSenderId(), type, Msg.Other_FILE_TYPE, groupMessageBean.getContent(), roomName, senderAvatarPath, filePath,false);
                    msg.setId(groupMessageBean.getId());
                    msgList.add(msg);
                }

                //   MessagesRequest.getImage(msgList, type, fileServerPath, roomName, senderAvatarPath);
            }

        } else {
            String senderAvatarPath = groupMessageBean.getSenderAvatarServerPath() == null ? groupMessageBean.getSenderAvatarLocalPath() : groupMessageBean.getSenderAvatarServerPath();
            final Msg[] msg = {null};
            String content = groupMessageBean.getContent();
            senderId = groupMessageBean.getSenderId();
            int type = userId.equals(senderId) ? Msg.TYPE_SEND : Msg.TYPE_RECEIVE;
            if (type == Msg.TYPE_RECEIVE && senderAvatarPath.contains("/")) {
                senderAvatarPath = Constant.IMAGE_PATH + senderAvatarPath.substring(senderAvatarPath.lastIndexOf("/") + 1);
                LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                Bitmap bitmap = (Bitmap) lruCache.get(senderAvatarPath.lastIndexOf("/"));
                //Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(senderAvatarPath.substring(senderAvatarPath.lastIndexOf("/")));
                if (bitmap == null) {
                    bitmap = BitmapFactory.decodeFile(senderAvatarPath);
                    if (bitmap == null) {
                        String finalSenderAvatarPath = senderAvatarPath;
                        UserInfoRequest.getAvatar(new Handler(new Handler.Callback() {
                            @Override
                            public boolean handleMessage(@NonNull Message message) {
                                GlobalAssistMap.putObject(groupMessageBean.getSenderId() + "Avatar", finalSenderAvatarPath);

                                if (groupMessageBean.getSignStatus() == 2) {
                                    msg[0] = new Msg(groupMessageBean.getSenderId(), groupMessageBean.getRoomName(), Msg.RECALL_TYPE, null, type, finalSenderAvatarPath,false);
                                    msgList.add(msg[0]);
                                    return true;
                                }

                                msg[0] = new Msg(groupMessageBean.getSenderId(), groupMessageBean.getRoomName(), Msg.WORD_TYPE, content, type, finalSenderAvatarPath,false);
                                msg[0].setId(groupMessageBean.getId());
                                msgList.add(msg[0]);
                                return true;
                            }
                        }), groupMessageBean.getSenderAvatarServerPath());
                    } else {

                        if (groupMessageBean.getSignStatus() == 2) {
                            msg[0] = new Msg(groupMessageBean.getSenderId(), groupMessageBean.getRoomName(), Msg.RECALL_TYPE, content, type, senderAvatarPath,false);
                            msgList.add(msg[0]);
                            return;
                        }

                        msg[0] = new Msg(groupMessageBean.getSenderId(), groupMessageBean.getRoomName(), Msg.WORD_TYPE, content, type, senderAvatarPath,false);
                        msg[0].setId(groupMessageBean.getId());
                        msgList.add(msg[0]);
                    }
                } else {

                    if (groupMessageBean.getSignStatus() == 2) {
                        msg[0] = new Msg(groupMessageBean.getSenderId(), groupMessageBean.getRoomName(), Msg.RECALL_TYPE, content, type, senderAvatarPath,false);
                        msgList.add(msg[0]);
                        return;
                    }

                    msg[0] = new Msg(groupMessageBean.getSenderId(), groupMessageBean.getRoomName(), Msg.WORD_TYPE, content, type, senderAvatarPath,false);
                    msg[0].setId(groupMessageBean.getId());
                    msgList.add(msg[0]);
                }
            } else {

                if (groupMessageBean.getSignStatus() == 2) {
                    msg[0] = new Msg(groupMessageBean.getSenderId(), groupMessageBean.getRoomName(), Msg.RECALL_TYPE, content, type, groupMessageBean.getSenderAvatarLocalPath(),false);
                    msgList.add(msg[0]);
                    GlobalAssistMap.putObject(groupMessageBean.getSenderId() + "Avatar", groupMessageBean.getSenderAvatarLocalPath());
                    return;
                }
                msg[0] = new Msg(groupMessageBean.getSenderId(), groupMessageBean.getRoomName(), Msg.WORD_TYPE, content, type, groupMessageBean.getSenderAvatarLocalPath(),false);
                msg[0].setId(groupMessageBean.getId());
                msgList.add(msg[0]);
                GlobalAssistMap.putObject(groupMessageBean.getSenderId() + "Avatar", groupMessageBean.getSenderAvatarLocalPath());
            }

        }

    }


    public static void upLoadImage(String messageBean) {
        //MediaType 设置Content-Type 标头中包含的媒体类型值
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , messageBean);

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(HttpConstant.HTTP_PREFIX + "/uploadImage")
                .post(requestBody)
                .build();
        Call call = httpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });

    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void getImage(String filePath,Handler handler) {
        MessageBean messageBean = new MessageBean();
        messageBean.setFilePath(filePath);

        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , new Gson().toJson(messageBean));

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .post(requestBody)
                .url(HttpConstant.HTTP_PREFIX + "/getImage")
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String resBody = response.body().string();
                MessageBean messageBean = new Gson().fromJson(resBody, MessageBean.class);
                if (messageBean == null) {
                    return;
                }
                String content = messageBean.getContent();
                byte[] by = Base64.getDecoder().decode(content);
                String cacheKey = filePath.substring(filePath.lastIndexOf("/") + 1);
                Bitmap bitmap = BitmapFactory.decodeByteArray(by, 0, by.length);
                LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                lruCache.put(cacheKey, bitmap);

                if(handler != null){
                    handler.sendMessage(handler.obtainMessage(1,Constant.SUCCESS));
                }
                //GlobalAssistMap.putObject(cacheKey, bitmap);
                by = null;

            }
        });


    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void getFile(Handler handler, String filePath) {


        MessageBean messageBean = new MessageBean();
        messageBean.setFilePath(filePath);

        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , new Gson().toJson(messageBean));

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .post(requestBody)
                .url(HttpConstant.HTTP_PREFIX + "/getFile")
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String resBody = response.body().string();
                MessageBean messageBean = new Gson().fromJson(resBody, MessageBean.class);
                if (messageBean == null) {
                    return;
                }
                String content = messageBean.getContent();

                try {
                    byte[] by = Base64.getDecoder().decode(content);
                    String path = Constant.FILE_PATH + filePath.substring(filePath.lastIndexOf("/") + 1);
                    OutputStream out = new FileOutputStream(path);
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);
                    bufferedOutputStream.write(by);
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                    out.close();
                    handler.sendMessage(handler.obtainMessage(1, Constant.SUCCESS));

                } catch (Exception e) {

                }
            }
        });

    }


    public static void upLoadVideo(MessageBean originMessageBean, Bitmap videoThumbBitmap) {
//        final MediaType FORM_FILE_TYPE = MediaType.parse("video/mp4");
//        File file = new File(messageBean.getFilePath());
//        RequestBody requestBody_video = RequestBody.create(FORM_FILE_TYPE, file);
//        RequestBody requestBody = new MultipartBody.Builder()
//                .addFormDataPart("file", file.getName(), requestBody_video)
//                .build();

        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , new Gson().toJson(originMessageBean));

        Request request = new Request.Builder()
                .get()
                .post(requestBody)
                .url(HttpConstant.HTTP_PREFIX + "/uploadImage")
                .build();


        OkHttpClient httpClient = new OkHttpClient();
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                int code = response.code();
                if (code == 200) {

                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    videoThumbBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                    byte[] byteArray = byteArrayOutputStream.toByteArray();
                    byte[] encode = new byte[0];
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        encode = Base64.getEncoder().encode(byteArray);
                    }

                    String bytes = new String(encode);
                    String suffix = originMessageBean.getFilePath().substring(originMessageBean.getFilePath().lastIndexOf("/") + 1, originMessageBean.getFilePath().lastIndexOf(".")) + ".jpeg";
                    MessageBean messageBean = new MessageBean();
                    messageBean.setSenderId(GlobalAssistMap.getObject("userId").toString());
                    messageBean.setContent(bytes);
                    messageBean.setRoomName(originMessageBean.getRoomName());
                    messageBean.setImei((String) GlobalAssistMap.getObject("imei"));
                    messageBean.setOneToOne(originMessageBean.isOneToOne());
                    messageBean.setReceiverId(originMessageBean.getReceiverId());
                    messageBean.setLocalMsdId(originMessageBean.getLocalMsdId());
                    messageBean.setFilePath(originMessageBean.getFilePath());
                    messageBean.setFileName(suffix);
                    messageBean.setMsgType(3);
                    messageBean.setActionType(1);

                    Date date = new Date();
                    @SuppressLint("SimpleDateFormat") String dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
                    messageBean.setSendTime(dateFormat);
                    UserInfoBean userInfoBean = (UserInfoBean) GlobalAssistMap.getObject("userInfo");
                    messageBean.setSenderName(userInfoBean.getNickname());
                    messageBean.setField(GlobalAssistMap.getObject("field").toString());
                    messageBean.setSenderAvatarPath(userInfoBean.getAvatarUrl());
                    MessagesRequest.upLoadImage(new Gson().toJson(messageBean));
                }

            }
        });

    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void getVideo(Handler handler, String filePath) {


        MessageBean messageBean = new MessageBean();
        messageBean.setFilePath(filePath);

        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , new Gson().toJson(messageBean));

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .post(requestBody)
                .url(HttpConstant.HTTP_PREFIX + "/getFile")
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String resBody = response.body().string();
                MessageBean messageBean = new Gson().fromJson(resBody, MessageBean.class);
                if (messageBean == null) {
                    return;
                }
                String content = messageBean.getContent();
                try {
                    byte[] by = Base64.getDecoder().decode(content);
                    String path = Constant.VIDEO_PATH + filePath.substring(filePath.lastIndexOf("/") + 1);
                    OutputStream out = new FileOutputStream(path);
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(out);
                    bufferedOutputStream.write(by);
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                    out.close();
                    handler.sendMessage(handler.obtainMessage(1, Constant.SUCCESS));

                } catch (Exception e) {

                }
            }
        });

    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void getVideoImage(String filePath) {


        MessageBean messageBean = new MessageBean();
        messageBean.setFilePath(filePath);

        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , new Gson().toJson(messageBean));

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .post(requestBody)
                .url(HttpConstant.HTTP_PREFIX + "/getImage")
                .build();


        Response response = null;
        try {
            httpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String resBody = response.body().string();
                    MessageBean messageBean = new Gson().fromJson(resBody, MessageBean.class);
                    if (messageBean == null) {
                        return;
                    }

                    String content = messageBean.getContent();
                    try {
                        byte[] by = Base64.getDecoder().decode(content);
                        Bitmap bitmap = BitmapFactory.decodeByteArray(by, 0, by.length);
                        LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                        lruCache.put(filePath.substring(filePath.lastIndexOf("/") + 1), bitmap);
                        // GlobalAssistMap.putObject(filePath.substring(filePath.lastIndexOf("/") + 1), bitmap);
                        by = null;


                    } catch (Exception e) {

                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void searchChatRecord(MessageBean messageBean, Handler handler) {


        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , new Gson().toJson(messageBean));

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .post(requestBody)
                .url(HttpConstant.HTTP_PREFIX + "/searchChatRecord")
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String resBody = response.body().string();
                List<ChatRecordBean> chatRecordBeanList = new Gson().fromJson(resBody, new TypeToken<List<ChatRecordBean>>() {
                }.getType());

                if (chatRecordBeanList != null) {
                    handler.sendMessage(handler.obtainMessage(1, chatRecordBeanList));
                }

            }
        });

    }

    public static void getRecentMessage(MessageBean messageBean, Handler handler) {


        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , new Gson().toJson(messageBean));

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .post(requestBody)
                .url(HttpConstant.HTTP_PREFIX + "/getRecentMessage")
                .build();

        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String resBody = response.body().string();
                List<ChatRecordBean> chatRecordBeanList = new Gson().fromJson(resBody, new TypeToken<List<ChatRecordBean>>() {
                }.getType());

                if (chatRecordBeanList != null) {
                    handler.sendMessage(handler.obtainMessage(1, chatRecordBeanList));
                }

            }
        });

    }


    public static void getOneToOneMessages(Handler handler, String roomName) {

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(HttpConstant.HTTP_PREFIX + "/getOneToOneMessages/" + roomName)
                .build();

        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Object context = GlobalAssistMap.getObject("context");
                AlterUtils.alertByToastInSonThread((Context) context, "获取消息列表失败");
            }

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (response.code() != 200) return;

                String messages = response.body().string();
                List<OneToOneMessageBean> messageList = new Gson().fromJson(messages, new TypeToken<List<OneToOneMessageBean>>() {
                }.getType());

                if (messageList == null || messageList.size() == 0) {
                    return;
                }

                String userId = (String) GlobalAssistMap.getObject("userId");
                if (userId == null) {
                    try {
                        Thread.sleep(100);
                        userId = (String) GlobalAssistMap.getObject("userId");
                        if (userId == null) {
                            Thread.sleep(200);
                            userId = (String) GlobalAssistMap.getObject("userId");
                            if (userId == null) {
                                Thread.sleep(500);
                                userId = (String) GlobalAssistMap.getObject("userId");
                            }
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                if (userId == null) {
                    return;
                }


                List<Msg> msgList = new ArrayList<>();

                int size = messageList.size();

                if (size > 30) {

                    for (int i = 0; i < 10; i++) {
                        GlobalAssistMap.putObject(i + "msgList", new ArrayList<Msg>());
                    }

                    int step = size / 10;

                    CountDownLatch countDownLatch = new CountDownLatch(10);

                    for (int i = 0; i < 10; i++) {
                        int finalI = i;
                        String finalUserId = userId;
                        GlobalThreadPool.buildThreadPool().execute(new Runnable() {
                            @Override
                            public void run() {

                                List<Msg> cacheList = (List<Msg>) GlobalAssistMap.getObject(finalI + "msgList");

                                for (int j = finalI * step; j < (finalI == 9 ? size : finalI * step + step); j++) {
                                    initOneToOneMessage(messageList.get(j), cacheList, finalUserId);
                                }
                                countDownLatch.countDown();
                            }
                        });
                    }
                    try {

                        countDownLatch.await();

                        for (int i = 0; i < 10; i++) {
                            List<Msg> cacheList = (List<Msg>) GlobalAssistMap.getObject(i + "msgList");
                            msgList.addAll(cacheList);
                            GlobalAssistMap.removeObject(i + "msgList");
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    for (OneToOneMessageBean oneToOneMessageBean : messageList) {
                        initOneToOneMessage(oneToOneMessageBean, msgList, userId);
                    }
                }

                handler.sendMessage(handler.obtainMessage(1, msgList));
            }
        });


    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private static void initOneToOneMessage(OneToOneMessageBean oneToOneMessageBean, List<Msg> msgList, String userId) {


        String senderId = oneToOneMessageBean.getSenderId();


        if (oneToOneMessageBean.getMsgType() != 0) {

            int type = userId.equals(senderId) ? Msg.TYPE_SEND : Msg.TYPE_RECEIVE;

            if (type == Msg.TYPE_SEND) {

                Msg msg = null;

                if (oneToOneMessageBean.getSignStatus() == 2) {
                    msg = new Msg(oneToOneMessageBean.getSenderId(), Msg.TYPE_SEND, Msg.RECALL_TYPE, "", oneToOneMessageBean.getRoomName(), oneToOneMessageBean.getSenderAvatarLocalPath(), null,true);
                    msgList.add(msg);
                    return;
                }

                if (oneToOneMessageBean.getMsgType() == 1) {
                    msg = new Msg(oneToOneMessageBean.getSenderId(), type, Msg.Other_FILE_TYPE, oneToOneMessageBean.getFilePath(), oneToOneMessageBean.getRoomName(), oneToOneMessageBean.getSenderAvatarLocalPath(), null,true);
                } else if (oneToOneMessageBean.getMsgType() == 2) {
                    String suf = oneToOneMessageBean.getFileSize();
                    msg = new Msg(oneToOneMessageBean.getSenderId(), type, Msg.Other_FILE_TYPE, oneToOneMessageBean.getFilePath(), oneToOneMessageBean.getRoomName(), oneToOneMessageBean.getSenderAvatarLocalPath(), oneToOneMessageBean.getFilePath().substring(oneToOneMessageBean.getFilePath().lastIndexOf("/") + 1) + " " + suf,true);
                } else if (oneToOneMessageBean.getMsgType() == 3) {
                    String videoCacheKey = oneToOneMessageBean.getFilePath().substring(oneToOneMessageBean.getFilePath().lastIndexOf("/") + 1);

                    LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                    Bitmap bitmap = (Bitmap) lruCache.get(videoCacheKey);
                    //Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(videoCacheKey);
                    if (bitmap == null) {
                        getVideoImage(oneToOneMessageBean.getContent());
                    }
                    String filePath = oneToOneMessageBean.getContent();
                    filePath = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf(".")) + ".mp4 ";
                    msg = new Msg(oneToOneMessageBean.getSenderId(), type, Msg.Other_FILE_TYPE, oneToOneMessageBean.getFilePath(), oneToOneMessageBean.getRoomName(), oneToOneMessageBean.getSenderAvatarLocalPath(), filePath,true);
                }
                assert msg != null;
                msg.setId(oneToOneMessageBean.getId());
                msgList.add(msg);

            } else {

                String fileServerPath = oneToOneMessageBean.getContent();

                if (fileServerPath == null) {
                    return;
                }

                String senderAvatarPath = (oneToOneMessageBean.getSenderAvatarServerPath() == null || oneToOneMessageBean.getSenderAvatarServerPath().equals("")) ? oneToOneMessageBean.getSenderAvatarLocalPath() : oneToOneMessageBean.getSenderAvatarServerPath();

                if (senderAvatarPath.contains("/")) {

                    senderAvatarPath = Constant.IMAGE_PATH + senderAvatarPath.substring(senderAvatarPath.lastIndexOf("/") + 1);

                    String finalSenderAvatarPath = senderAvatarPath;

                    LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                    final Bitmap[] bitmap = {(Bitmap) lruCache.get(finalSenderAvatarPath.substring(finalSenderAvatarPath.lastIndexOf("/")))};
                    // final Bitmap[] bitmap = {(Bitmap) GlobalAssistMap.getObject(finalSenderAvatarPath.substring(finalSenderAvatarPath.lastIndexOf("/")))};
                    if (bitmap[0] == null) {
                        bitmap[0] = BitmapFactory.decodeFile(finalSenderAvatarPath);
                        if (bitmap[0] == null) {
                            UserInfoRequest.getAvatar(new Handler(new Handler.Callback() {
                                @Override
                                public boolean handleMessage(@NonNull Message message) {
                                    //GlobalAssistMap.putObject(oneToOneMessageBean.getSenderId() + "Avatar", finalSenderAvatarPath);
                                    bitmap[0] = BitmapFactory.decodeFile(finalSenderAvatarPath);
                                    lruCache.put(finalSenderAvatarPath.substring(finalSenderAvatarPath.lastIndexOf("/")), bitmap[0]);
                                    //GlobalAssistMap.putObject(finalSenderAvatarPath.substring(finalSenderAvatarPath.lastIndexOf("/")), bitmap[0]);
                                    return true;
                                }
                            }), oneToOneMessageBean.getSenderAvatarServerPath());
                        } else {
                            lruCache.put(finalSenderAvatarPath.substring(finalSenderAvatarPath.lastIndexOf("/")), bitmap[0]);
                            //GlobalAssistMap.putObject(finalSenderAvatarPath.substring(finalSenderAvatarPath.lastIndexOf("/")), bitmap[0]);
                        }

                    }

                }

                GlobalAssistMap.putObject(oneToOneMessageBean.getSenderId() + "Avatar", senderAvatarPath);

                if (oneToOneMessageBean.getSignStatus() == 2) {
                    Msg msg = new Msg(oneToOneMessageBean.getSenderId(), oneToOneMessageBean.getRoomName(), Msg.RECALL_TYPE, null, Msg.TYPE_RECEIVE, senderAvatarPath,true);
                    msgList.add(msg);
                    return;
                }

                if (oneToOneMessageBean.getMsgType() == 1) {

                    String cacheKey = oneToOneMessageBean.getFilePath().substring(oneToOneMessageBean.getFilePath().lastIndexOf("/") + 1);

                    LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                    Bitmap bitmap = (Bitmap) lruCache.get(cacheKey);
                    //Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(cacheKey);
                    if (bitmap == null) {
                        MessagesRequest.getImage(fileServerPath,null);
                    }
                    Msg msg = new Msg(oneToOneMessageBean.getSenderId(), Msg.TYPE_RECEIVE, Msg.Other_FILE_TYPE, cacheKey, oneToOneMessageBean.getRoomName(), senderAvatarPath, null,true);
                    msg.setId(oneToOneMessageBean.getId());
                    msgList.add(msg);
                } else if (oneToOneMessageBean.getMsgType() == 2) {
                    Msg msg = new Msg(oneToOneMessageBean.getSenderId(), type, Msg.Other_FILE_TYPE, oneToOneMessageBean.getContent(), oneToOneMessageBean.getRoomName(), senderAvatarPath, oneToOneMessageBean.getFilePath().substring(oneToOneMessageBean.getFilePath().lastIndexOf("/") + 1) + "  " + oneToOneMessageBean.getFileSize(),true);
                    msg.setId(oneToOneMessageBean.getId());
                    msgList.add(msg);
                } else if (oneToOneMessageBean.getMsgType() == 3) {

                    String cacheKey = oneToOneMessageBean.getContent().substring(oneToOneMessageBean.getContent().lastIndexOf("/") + 1);

                    LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                    Bitmap bitmap = (Bitmap) lruCache.get(cacheKey);
                    //Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(cacheKey);
                    if (bitmap == null) {
                        getVideoImage(oneToOneMessageBean.getContent());
                    }
                    String filePath = oneToOneMessageBean.getContent();
                    filePath = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf(".")) + ".mp4 ";
                    Msg msg = new Msg(oneToOneMessageBean.getSenderId(), type, Msg.Other_FILE_TYPE, oneToOneMessageBean.getContent(), oneToOneMessageBean.getRoomName(), senderAvatarPath, filePath,true);
                    msg.setId(oneToOneMessageBean.getId());
                    msgList.add(msg);
                }

                //   MessagesRequest.getImage(msgList, type, fileServerPath, roomName, senderAvatarPath);
            }

        } else {
            String senderAvatarPath = oneToOneMessageBean.getSenderAvatarServerPath() == null ? oneToOneMessageBean.getSenderAvatarLocalPath() : oneToOneMessageBean.getSenderAvatarServerPath();
            final Msg[] msg = {null};
            String content = oneToOneMessageBean.getContent();
            senderId = oneToOneMessageBean.getSenderId();
            int type = userId.equals(senderId) ? Msg.TYPE_SEND : Msg.TYPE_RECEIVE;
            if (type == Msg.TYPE_RECEIVE && senderAvatarPath.contains("/")) {
                senderAvatarPath = Constant.IMAGE_PATH + senderAvatarPath.substring(senderAvatarPath.lastIndexOf("/") + 1);
                LRUCache lruCache = (LRUCache) GlobalAssistMap.getObject("lruCache");
                Bitmap bitmap = (Bitmap) lruCache.get(senderAvatarPath.lastIndexOf("/") + 1);
                //Bitmap bitmap = (Bitmap) GlobalAssistMap.getObject(senderAvatarPath.substring(senderAvatarPath.lastIndexOf("/")));
                if (bitmap == null) {
                    bitmap = BitmapFactory.decodeFile(senderAvatarPath);
                    if (bitmap == null) {
                        String finalSenderAvatarPath = senderAvatarPath;
                        UserInfoRequest.getAvatar(new Handler(new Handler.Callback() {
                            @Override
                            public boolean handleMessage(@NonNull Message message) {
                                GlobalAssistMap.putObject(oneToOneMessageBean.getSenderId() + "Avatar", finalSenderAvatarPath);

                                if (oneToOneMessageBean.getSignStatus() == 2) {
                                    msg[0] = new Msg(oneToOneMessageBean.getSenderId(), oneToOneMessageBean.getRoomName(), Msg.RECALL_TYPE, null, type, finalSenderAvatarPath,true);
                                    msgList.add(msg[0]);
                                    return true;
                                }

                                msg[0] = new Msg(oneToOneMessageBean.getSenderId(), oneToOneMessageBean.getRoomName(), Msg.WORD_TYPE, content, type, finalSenderAvatarPath,true);
                                msg[0].setId(oneToOneMessageBean.getId());
                                msgList.add(msg[0]);
                                return true;
                            }
                        }), oneToOneMessageBean.getSenderAvatarServerPath());
                    } else {

                        if (oneToOneMessageBean.getSignStatus() == 2) {
                            msg[0] = new Msg(oneToOneMessageBean.getSenderId(), oneToOneMessageBean.getRoomName(), Msg.RECALL_TYPE, content, type, senderAvatarPath,true);
                            msgList.add(msg[0]);
                            return;
                        }

                        msg[0] = new Msg(oneToOneMessageBean.getSenderId(), oneToOneMessageBean.getRoomName(), Msg.WORD_TYPE, content, type, senderAvatarPath,true);
                        msg[0].setId(oneToOneMessageBean.getId());
                        msgList.add(msg[0]);
                    }
                } else {

                    if (oneToOneMessageBean.getSignStatus() == 2) {
                        msg[0] = new Msg(oneToOneMessageBean.getSenderId(), oneToOneMessageBean.getRoomName(), Msg.RECALL_TYPE, content, type, senderAvatarPath,true);
                        msgList.add(msg[0]);
                        return;
                    }

                    msg[0] = new Msg(oneToOneMessageBean.getSenderId(), oneToOneMessageBean.getRoomName(), Msg.WORD_TYPE, content, type, senderAvatarPath,true);
                    msg[0].setId(oneToOneMessageBean.getId());
                    msgList.add(msg[0]);
                }
            } else {

                if (oneToOneMessageBean.getSignStatus() == 2) {
                    msg[0] = new Msg(oneToOneMessageBean.getSenderId(), oneToOneMessageBean.getRoomName(), Msg.RECALL_TYPE, content, type, oneToOneMessageBean.getSenderAvatarLocalPath(),true);
                    msgList.add(msg[0]);
                    GlobalAssistMap.putObject(oneToOneMessageBean.getSenderId() + "Avatar", oneToOneMessageBean.getSenderAvatarLocalPath());
                    return;
                }
                msg[0] = new Msg(oneToOneMessageBean.getSenderId(), oneToOneMessageBean.getRoomName(), Msg.WORD_TYPE, content, type, oneToOneMessageBean.getSenderAvatarLocalPath(),true);
                msg[0].setId(oneToOneMessageBean.getId());
                msgList.add(msg[0]);
                GlobalAssistMap.putObject(oneToOneMessageBean.getSenderId() + "Avatar", oneToOneMessageBean.getSenderAvatarLocalPath());
            }

        }


    }


    public static void updateMessageStatus(String roomName) {

        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(HttpConstant.HTTP_PREFIX + "/updateMessageStatus/" + roomName)
                .build();

        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });


    }

}
